import { ref, watch, unref, onMounted } from "vue";

/**
 * 表格分页查询hooks
 * @param {*} config
 * @returns
 */
export const useTable = (config) => {
  const { immediate = true } = config;

  /** 表格加载状态 */
  const tableLoading = ref(false);
  /** 分页-当前页 */
  const pageNum = ref(1);
  /** 分页-分页数量 */
  const pageSize = ref(20);
  /** 总数 */
  const total = ref(0);
  /** 表格数据列表 */
  const tableData = ref([]);

  watch(
    () => pageNum.value,
    () => {
      methods.getList();
    }
  );

  watch(
    () => pageSize.value,
    () => {
      // 当前页不为1时，修改页数后会导致多次调用getList方法
      if (unref(pageNum) === 1) {
        methods.getList();
      } else {
        pageNum.value = 1;
        methods.getList();
      }
    }
  );

  onMounted(() => {
    if (immediate) {
      methods.getList();
    }
  });

  const methods = {
    /**
     * 获取表格数据
     */
    getList: async (data) => {
      tableLoading.value = true;
      const res = await config.fetchDataApi(data);
      tableData.value = res.list;
      total.value = res.total;
      tableLoading.value = false;
    },

    formattingTime: (create_time) => {
      const data = new Date(create_time);
      const year = data.getFullYear();
      const month = data.getMonth() + 1;
      const date = data.getDate();
      return year + "年" + month + "月" + date + "日";
    },

    refresh: () => {
      methods.getList();
    },
  };

  return {
    tableMethods: methods,
    tableState: {
      tableData,
      tableLoading,
      total,
    },
    pagination: {
      pageNum,
      pageSize,
    },
  };
};
